package com.gitee.cui.netty.bytebuf;

import com.gitee.cui.util.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 缓冲区类型测试类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 13:06
 **/
public class ByteBufTypeTest {

    /**
     * java堆缓冲区测试
     */
    @Test
    public void heapBufferTest() {
        ByteBuf heapBuffer = ByteBufAllocator.DEFAULT.heapBuffer();
        heapBuffer.writeBytes("测试Java堆缓冲区".getBytes(StandardCharsets.UTF_8));
        if (heapBuffer.hasArray()) {
            byte[] array = heapBuffer.array();
            int offset = heapBuffer.arrayOffset() + heapBuffer.readerIndex();
            int length = heapBuffer.readableBytes();
            Logger.info(new String(array, offset, length, StandardCharsets.UTF_8));
        }
        heapBuffer.release();
    }

    /**
     * 测试堆外缓冲区
     */
    @Test
    public void directBufferTest() {
        ByteBuf directBuffer = ByteBufAllocator.DEFAULT.directBuffer();
        directBuffer.writeBytes("测试堆外缓冲区".getBytes(StandardCharsets.UTF_8));
        if (!directBuffer.hasArray()) {
            int length = directBuffer.readableBytes();
            byte[] array = new byte[length];
            // 需要将堆外缓冲区的内容，读到Java程序的字节数组中
            directBuffer.getBytes(directBuffer.readerIndex(), array);
            Logger.info(new String(array, StandardCharsets.UTF_8));
        }
        directBuffer.release();
    }
}
